package com.yuanmeng.common.core.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuanmeng.common.core.enums.ErrorCodeEnum;
import com.yuanmeng.common.core.utils.StringUtils;

import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.tm.api.GlobalTransactionContext;

/**
 * 业务异常
 * 
 * @author 安然
 */
public final class ServiceException extends RuntimeException {
    private static final Logger logger           = LoggerFactory.getLogger(ServiceException.class);
    private static final long   serialVersionUID = 1L;

    /**
     * 错误码
     */
    private Integer             code;

    /**
     * 错误提示
     */
    private String              message;

    /**
     * 错误明细，内部调试错误
     *
     * 和 {@link CommonResult#getDetailMessage()} 一致的设计
     */
    private String              detailMessage;

    /**
     * 空构造方法，避免反序列化问题
     */
    public ServiceException() {
    }

    public ServiceException(String message) {
        this.message = message;
        globalTransactionId();
    }

    public ServiceException(String message, Integer code) {
        this.message = message;
        this.code = code;
        globalTransactionId();
    }

    public String getDetailMessage() {
        return detailMessage;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public Integer getCode() {
        return code;
    }

    public ServiceException setMessage(String message) {
        this.message = message;
        return this;
    }

    public ServiceException setDetailMessage(String detailMessage) {
        this.detailMessage = detailMessage;
        return this;
    }

    public ServiceException(ErrorCodeEnum errorCodeEnum) {
        this.message = errorCodeEnum.getMessage();
        globalTransactionId();
    }

    private void globalTransactionId() {
        if (StringUtils.isNotBlank(RootContext.getXID())) {
            try {
                logger.error("GlobalTransaction服务异常手动回滚走这里");
                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            } catch (TransactionException e) {
                e.printStackTrace();
            }
        }
    }
}